//
// Created by 11510 on 2025/10/2.
//

#include "CommandFactory.h"
#include "AcquireCommand.h"
#include "PingCommand.h"
#include "HistoryCommand.h"
#include "GetCommand.h"
#include "LsCommand.h"
#include "ManCommand.h"
#include "SaveCommand.h"
#include "ServiceCommand.h"
#include "LiveCommand.h"
#include "SetCommand.h"
#include "UnliveCommand.h"
#include "HelpCommand.h"
// Helper macro to register commands
#define REGISTER_COMMAND(NAME, TYPE) \
    static bool __reg_##TYPE = [](){ \
        xclib_client::CommandFactory::instance().registerCommand(NAME, [](xclib_client::CommandContext ctx){ return std::make_unique<xclib_client::TYPE>(ctx); }); \
        return true; }();

REGISTER_COMMAND("acquire", AcquireCommand)
REGISTER_COMMAND("ping", PingCommand)
REGISTER_COMMAND("history", HistoryCommand)
REGISTER_COMMAND("get", GetCommand)
REGISTER_COMMAND("live", LiveCommand)
REGISTER_COMMAND("ls", LsCommand)
REGISTER_COMMAND("man", ManCommand)
REGISTER_COMMAND("save", SaveCommand)
REGISTER_COMMAND("service", ServiceCommand)
REGISTER_COMMAND("set", SetCommand)
REGISTER_COMMAND("unlive", UnliveCommand)
REGISTER_COMMAND("help", HelpCommand)

xclib_client::CommandFactory &xclib_client::CommandFactory::instance() {
    static CommandFactory f;
    return f;
}

void xclib_client::CommandFactory::registerCommand(const std::string &name, CommandCreator creator) {
    registry[name] = creator;
}

bool xclib_client::CommandFactory::has(const std::string &name) const {
    return registry.count(name);
}

std::unique_ptr<xclib_client::ICommand> xclib_client::CommandFactory::create(const std::string &name, CommandContext ctx) const {
    auto it = registry.find(name);
    if (it == registry.end())
        return nullptr;
    return it->second(ctx);
}

std::vector<std::string> xclib_client::CommandFactory::listCommands() const {
    std::vector<std::string> keys;
    for (auto &p: registry)
        keys.push_back(p.first);
    sort(keys.begin(), keys.end());
    return keys;
}












